package com.lxw;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Consumer02 {
    private static final String QUEUE = "hello world";

    public static void main(String[] args) throws Exception {
        //创建ConnectionFactory对象,并设置属性
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("guest");
        connectionFactory.setPassword("guest");
        //通过工厂获取connection
        Connection connection = connectionFactory.newConnection();
        //通过Connection获取Channel
        Channel channel = connection.createChannel();
        //通过Channel声明队列
        /*String queue, boolean durable, boolean exclusive, boolean autoDelete,
        Map<String, Object> arguments*/
        channel.queueDeclare(QUEUE, true, false, false, null);
        DefaultConsumer defaultConsumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag,
                                       Envelope envelope,
                                       AMQP.BasicProperties properties,
                                       byte[] body)
                    throws IOException {
                String exchange = envelope.getExchange();
                long deliveryTag = envelope.getDeliveryTag();
                String routingKey = envelope.getRoutingKey();
                String message = new String(body, "utf-8");
                System.out.println("receive message:"+message);
            }
        };
        channel.basicConsume(QUEUE,true,defaultConsumer);
    }
}
